<template>
  <section class="mobile-userinfo-page">
    <div v-if="titleInformation" class="title-box">
      <p class="title-value">{{ titleInformation[active][0] }}</p>
      <p class="title-sub">{{ titleInformation[active][2] }}</p>
    </div>
    <div class="content-box">
      <van-form ref="dataForm" :scroll-to-error="true" validate-trigger="onSubmit">
        <template v-if="active === 1">
          <van-field
            class="form-item-input"
            v-model="form.nickname"
            name="nickname"
            label="姓名"
            placeholder="请填写真实姓名，用于投递简历"
            maxlength="20"
            :rules="[{ required: true, message: '' }]"
          />
          <van-field class="form-item-right" name="sex" label="性别">
            <template #input>
              <van-radio-group v-model="form.sex" direction="horizontal">
                <van-radio name="女">女</van-radio>
                <van-radio name="男">男</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="clan"
            :value="form.clan"
            label="民族"
            placeholder="请选择民族"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowPicker('clan')"
          />
          <van-field class="form-item-right" name="identify" label="当前身份">
            <template #input>
              <van-radio-group v-model="form.identify" direction="horizontal">
                <van-radio
                  v-for="item in studentType"
                  :key="item.value"
                  :name="item.value"
                >
                  {{ item.label }}
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="political"
            :value="form.political"
            label="政治面貌"
            placeholder="请选择政治面貌"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowPicker('political')"
          />
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="datetimePicker"
            :value="form.birthday"
            label="出生年月"
            placeholder="请选择出生年月日"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowTime('birthday')"
          />
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="liveCityMobile"
            :value="form.liveCityMobile"
            label="现居住城市"
            placeholder="请选择现居住城市"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowArea('liveCityMobile')"
          />
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="nativePlaceMobile"
            :value="form.nativePlaceMobile"
            label="籍贯"
            placeholder="请选择籍贯"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowArea('nativePlaceMobile')"
          />
          <van-field
            class="form-item-input"
            v-model="form.mobile"
            type="tel"
            name="mobile"
            label="手机号码"
            placeholder="请输入手机号码"
            :rules="[{ required: true, message: '' }]"
            disabled
          />
          <van-field
            class="form-item-input"
            v-model="form.email"
            name="email"
            label="邮箱地址"
            placeholder="请输入邮箱地址"
            :rules="[{ message: '', validator: validataEmail }]"
          />
          <van-field class="form-item-right" name="jobStatus" label="当前状态">
            <template #input>
              <van-radio-group v-model="form.jobStatus" direction="horizontal">
                <van-radio name="正在实习">正在实习</van-radio>
                <van-radio name="暂无实习">暂无实习</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field class="form-item-right" name="inJobTime" label="入职时间">
            <template #input>
              <van-radio-group v-model="form.inJobTime" direction="horizontal">
                <van-radio name="随时入职">随时入职</van-radio>
                <van-radio name="2周内入职">2周内入职</van-radio>
                <van-radio name="时间待定">时间待定</van-radio>
              </van-radio-group>
            </template>
          </van-field>
        </template>
        <template v-if="active === 2">
          <van-field
            class="form-item-input"
            v-model="form.schoolName"
            name="schoolName"
            label="学校名称"
            placeholder="请输入学校名称"
            maxlength="20"
            :rules="[{ required: true, message: '' }]"
          />
          <van-field
            class="form-item-educational"
            name="educationalBackground"
            label="教育状态"
            :rules="[{ required: true, message: '', validator: validataEducational }]"
          >
            <template #input>
              <van-field
                class="form-item-input"
                readonly
                clickable
                v-model="form.educationalBackground"
                placeholder="请选择教育状态"
                right-icon="arrow"
                @click="onShowPicker('educationalBackground')"
              />
              <div class="form-item-educational-options">
                <van-radio-group v-model="form.diploma" direction="horizontal">
                  <van-radio name="1">有学位证书</van-radio>
                  <van-radio name="0">无学位证书</van-radio>
                </van-radio-group>
              </div>
              <div class="form-item-educational-options">
                <van-radio-group v-model="form.fullTime" direction="horizontal">
                  <van-radio name="1">全日制</van-radio>
                  <van-radio name="0">非全日制</van-radio>
                </van-radio-group>
              </div>
            </template>
          </van-field>
          <van-field
            class="form-item-educational"
            label="在校时间"
            name="intakeTime"
            v-model="form.intakeTime"
          >
            <template #input>
              <div class="form-item-times">
                <van-field
                  class="form-item-input"
                  readonly
                  clickable
                  v-model="form.intakeTime"
                  placeholder="开始日期"
                  @click="onShowTime('intakeTime')"
                  :rules="[{ required: true, message: '', validator: validataEducationalTime }]"
                />
                <span class="form-item-times-line">-</span>
                <van-field
                  class="form-item-input"
                  :class="{'disabled': isTillNowMobile}"
                  readonly
                  clickable
                  v-model="form.graduateTime"
                  placeholder="毕业日期"
                  right-icon="arrow"
                  :disabled="isTillNowMobile"
                  @click="onShowTime('graduateTime')"
                  :rules="[{  message: '', validator: validataEducationalTime }]"
                />
              </div>
              <div class="form-item-educational-options">
                <van-checkbox v-model="isTillNowMobile" shape="square">至今</van-checkbox>
              </div>
            </template>
          </van-field>
          <van-field
            v-if="isTillNowMobile"
            class="form-item-input"
            readonly
            clickable
            name="grade"
            :value="form.grade"
            label="所在年级"
            placeholder="请选择所在年级"
            right-icon="arrow"
            @click="onShowPicker('grade')"
            :rules="[{  message: '', validator: validataEducationalGrade }]"
          />
          <van-field
            class="form-item-input"
            v-model="form.major"
            name="major"
            label="所学专业"
            placeholder="请输入所学专业"
            maxlength="20"
            :rules="[{ required: true, message: '' }]"
          />
          <van-field class="form-item-right" name="isOverseasStudy" label="海外留学经历">
            <template #input>
              <van-radio-group v-model="form.isOverseasStudy" direction="horizontal">
                <van-radio name="无">无</van-radio>
                <van-radio name="有">有</van-radio>
              </van-radio-group>
            </template>
          </van-field>
        </template>
        <template v-if="active === 3">
          <van-field
            class="form-item-input"
            v-model="form.jobName"
            name="jobName"
            label="期望职位"
            placeholder="请选择期望行业，如：互联网/电子商务"
            maxlength="20"
            :rules="[{ required: true, message: '' }]"
          />
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="expectedIndustryMobile"
            :value="form.expectedIndustryMobile"
            label="期望行业"
            placeholder="请选择期望行业"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowBusinessArea('')"
          />
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="targetCityMobile"
            :value="form.targetCityMobile"
            label="期望城市"
            placeholder="请选择现居住城市"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowArea('targetCityMobile')"
          />
          <van-field
            class="form-item-educational form-item-salary"
            name="lowestSalary"
            :rules="[{  message: '', validator: validataLowestSalary }]"
          >
            <template #label>
              <div class="form-item-salary-label">
                <p>薪资要求</p>
                <p class="form-item-tip">(元/天)</p>
              </div>
            </template>
            <template #input>
              <div class="form-item-times">
                <van-field
                  class="form-item-input"
                  v-model="form.lowestSalary"
                  placeholder="最低要求"
                  type="number"
                  maxlength="4"
                />
                <span class="form-item-times-line">-</span>
                <van-field
                  class="form-item-input"
                  v-model="form.highestSalary"
                  placeholder="最高要求"
                  type="number"
                  maxlength="4"
                />
              </div>
              <div class="form-item-educational-tips">
                * 格式样例：1000
              </div>
            </template>
          </van-field>
        </template>
        <div class="step-box">
          <van-button plain type="info" v-if="active > 1" class="step-btn step-up" @click="pre()">
            上一步
          </van-button>
          <van-button type="info" v-if="active < 3" class="step-btn step-next"   @click="next()">
            下一步
          </van-button>
          <van-button type="info" v-if="active === 3" class="step-btn step-next" @click="finish()">
            完成
          </van-button>
        </div>
      </van-form>
    </div>
    <van-popup v-model="showTimePicker" position="bottom">
      <van-datetime-picker
        v-model="timePickerValue"
        :type="timePickerType"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onTimeConfirm"
        @cancel="onTimeCancel"
      />
    </van-popup>
    <van-popup v-model="brithdayRealPop" position="bottom">
      <van-datetime-picker
        v-model="brithdayShowDate"
        :type="timePickerType"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onTimeConfirm"
        @cancel="onTimeCancel"
      />
    </van-popup>
    <van-popup v-model="showArea" position="bottom">
      <van-cascader
        v-model="areaValue"
        title="请选择所在地区"
        :options="provinceAndCityData"
        :field-names="fieldNames"
        @close="showArea = false"
        @finish="onAreaConfirm"
      />
    </van-popup>
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :default-index="pickerIndex"
        :columns="pickerColumns"
        :value-key="pickerKeyName"
        @confirm="onPickerConfirm"
        @cancel="onPickerCancel"
      />
    </van-popup>
    <van-popup v-model="showBusinessArea" position="bottom">
      <van-cascader
        v-model="businessAreaValue"
        title="请选择行业"
        :options="businessAreaData"
        :field-names="fieldNames"
        @close="showBusinessArea = false"
        @finish="onBusinessAreaConfirm"
      />
    </van-popup>
  </section>
</template>

<script>
import moment from "moment";
export default {
  // 组件名称
  name: "",
  // 组件参数 接收来自父组件的数据
  props: {
    titleInformation: Object,
    form: Object,
    formRules: Object,
    studentType: Array,
    provinceAndCityData: Array,
    nationData: Array,
    politicalList: Array,
    educationalBackList: Array,
    isTillNow: Boolean,
    educationOptions: Array,
    businessAreaData: Array,
  },
  // 局部注册的组件
  components: {

  },
  watch: {
    isTillNow(status) {
      this.isTillNowMobile = status
    }
  },
  // 组件状态值
  data() {
    return {
      active: 1,

      isTillNowMobile: false,
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(),
      timePickerValue: '',
      timePickerType: '',
      timePickerKey: '',
      timePickerFmt: '',
      showTimePicker: false,

      selectLiveCity: [],
      selectNativePlace: [],
      selectTargetCity: [],
      showAreaKey: '',
      showArea: false,
      fieldNames: {
        text: 'label',
        value: 'value',
      },
      areaValue: '',
      selectBusiness: [],
      showBusinessArea: false,
      businessAreaValue: '',
      selectGrade: '',
      pickerIndex: 0,
      pickerKey: '',
      pickerKeyName: 'text',
      pickerColumns: [],
      showPicker: false,
      brithdayRealPop: false, // 生日额外弹出的日期组件，用于实现特殊逻辑
      brithdayShowDate: new Date() // 未注册 默认今天
    };
  },
  created() {
  },
  // 组件方法
  methods: {
    // 生日选择
    onShowTime(key) {
      if (this.isTillNowMobile && key === 'graduateTime') return
      this.timePickerValue = ''
      this.timePickerType = 'date'
      this.timePickerKey = key
      this.timePickerFmt = 'yyyy-MM-DD'
      this.minDate = new Date(1970, 0, 1)
      this.maxDate = new Date()
      if (this.form[key]) this.timePickerValue = new Date(this.form[key])
      if (key === 'intakeTime') {
        this.timePickerFmt = 'yyyy年MM月'
        if (this.form.graduateTime) {
          const time = this.form.graduateTime.replace('年', '-').replace('月', '')
          this.maxDate = new Date(time)
        }
        this.timePickerType = 'year-month'
      }
      if (key === 'graduateTime') {
        this.timePickerFmt = 'yyyy年MM月'
        // if (this.form.intakeTime) this.minDate = new Date(moment(this.form.intakeTime).format('yyyy-MM'))
        if (this.form.intakeTime) {
          const time = this.form.intakeTime.replace('年', '-').replace('月', '')
          this.minDate = new Date(time)
        }
        this.timePickerType = 'year-month'
      }
      /**
       * 骚逻辑：
       * - 第一次注册无数据时，组件弹出默认选中今天，而不是最早的1970年
       * - 如果已经有数据了就正常展示今天
       */
      if (key === 'birthday'){
        if (this.form.birthday) {
          this.brithdayShowDate = this.form.birthday
        }
        this.brithdayRealPop = true
      } else {
        this.showTimePicker = true
      }
    },
    onTimeConfirm(e) {
      this.showTimePicker = false
      this.brithdayRealPop = false
      this.form[this.timePickerKey] = moment(e).format(this.timePickerFmt)
    },
    onTimeCancel() {
      this.brithdayRealPop = false
      this.showTimePicker = false
      this.timePickerValue = ''
    },
    // 地区选择
    onShowArea(key) {
      this.showArea = true
      this.showAreaKey = key
      this.areaValue = ''
      if (key === 'liveCityMobile' && this.selectLiveCity.length) {
        this.areaValue = this.selectLiveCity[1].value
      }
      if (key === 'nativePlaceMobile' && this.selectNativePlace.length) {
        this.areaValue = this.selectNativePlace[1].value
      }
      if (key === 'targetCityMobile' && this.selectTargetCity.length) {
        this.areaValue = this.selectTargetCity[1].value
      }
    },
    onAreaConfirm({selectedOptions: arr}) {
      this.showArea = false
      const ids = []
      arr.map(v => ids.push(v.value))
      if (this.showAreaKey == 'liveCityMobile') {
        this.selectLiveCity = arr
        this.form.liveCityMobile = arr[1].label
        this.form.liveCity = ids
      }
      if (this.showAreaKey == 'nativePlaceMobile') {
        this.selectNativePlace = arr
        this.form.nativePlaceMobile = arr[1].label
        this.form.nativePlace = ids
      }
      if (this.showAreaKey == 'targetCityMobile') {
        this.selectTargetCity = arr
        this.form.targetCityMobile = arr[1].label
        this.form.targetCity = ids
      }
    },
    onChangeArea(picker, index, value) {
      console.log('onChangeArea', picker, index, value)
    },
    // 行业选择
    onShowBusinessArea() {
      this.businessAreaValue = ''
      if ( this.selectBusiness.length) {
        this.areaValue = this.selectBusiness[1].value
      }
      this.showBusinessArea = true
    },
    onBusinessAreaConfirm({selectedOptions: arr}) {
      this.showBusinessArea = false
      const ids = []
      arr.map(v => ids.push(v.value))
      this.selectBusiness = arr
      this.form.expectedIndustryMobile = arr[1].label
      this.form.expectedIndustry[0] = ids
    },
    // 下拉选择
    onShowPicker(key) {
      this.pickerKeyName = 'text'
      let pickerIndex = 0
      if (key === 'clan') {
        this.nationData.map((v, i) => {
          if (v === this.form[key]) pickerIndex = i
        })
        this.pickerColumns = this.nationData
      }
      if (key === 'political') {
        this.politicalList.map((v, i) => {
          if (v === this.form[key]) pickerIndex = i
        })
        this.pickerColumns = this.politicalList
      }
      if (key === 'educationalBackground') {
        this.educationalBackList.map((v, i) => {
          if (v === this.form[key]) pickerIndex = i
        })
        this.pickerColumns = this.educationalBackList
      }
      if (key === 'grade') {
        this.educationOptions.map((v, i) => {
          if (v.label === this.form[key]) pickerIndex = i
        })
        this.pickerColumns = this.educationOptions
        this.pickerKeyName = 'label'
      }
      this.pickerIndex = pickerIndex
      this.pickerKey = key
      this.showPicker = true
    },
    onPickerConfirm(e) {
      if (this.pickerKey === 'grade') {
        this.form[this.pickerKey] = e.label
        this.selectGrade = e
      } else {
        this.form[this.pickerKey] = e
      }
      if (this.pickerKey === 'educationalBackground') this.form.grade = ''
      this.onPickerCancel()
    },
    onPickerCancel() {
      this.showPicker = false
    },
    validataEmail(value) {
      return new Promise((resolve) => {
        let emailReg =
        /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
        if (value === "") {
          return resolve(false);;
        } else {
          if (emailReg.test(value)) {
            return resolve(true);
          } else {
            return resolve(false);;
          }
        }
      });
    },
    validataEducational() {
      return new Promise((resolve) => {
        if (this.form.educationalBackground === "") {
          return resolve(false);;
        } else {
          return resolve(true);
        }
      });
    },
    validataEducationalTime() {
      return new Promise((resolve) => {
        if ((this.form.intakeTime && this.isTillNowMobile)) {
          return resolve(true);
        } else if ((this.form.intakeTime && this.form.graduateTime)) {
          return resolve(true);
        } else {
          return resolve(false);
        }
      });
    },
    validataEducationalGrade(value) {
      return new Promise((resolve) => {
        if (!value && this.isTillNowMobile) {
          return resolve(false);;
        } else {
          return resolve(true);
        }
      });
    },
    validataLowestSalary() {
      let status = true
      if (this.form.lowestSalary === '' || this.form.highestSalary === '') {
        status = false;
      }
      if (Number(this.form.lowestSalary) > Number(this.form.highestSalary)) {
        status = false;
      }
      if (Number(this.form.lowestSalary) < 0 || Number(this.form.highestSalary) < 0) {
        status = false;
      }
      return status
    },
    onSubmit() {
      if (this.active < 3) {
        this.next()
      } else {
        this.finish()
      }
    },
    // 步骤条下一步的方法
    next() {
      this.$refs.dataForm.validate().then(() => {
        this.active += 1;
        setTimeout(() => {
          this.$refs.dataForm.resetValidation();
        });
      })
    },
    // 步骤条上一步的方法
    pre() {
      this.active -= 1;
    },
    finish() {
      this.$refs.dataForm.validate().then(() => {
        this.$emit('finish', {
          isTillNowMobile: this.isTillNowMobile
        })
      })
    }
  },
  beforeDestroy() {
  }
};
</script>
<style lang="less">
.van-tabs__line {
  background-color: #4677B9;
}
.van-cascader__option--selected {
  color: #4677B9;
}
.van-button--info {
  border: 1px solid #4677B9;
  background-color: #4677B9;
}
</style>
<style lang="less" scoped>
.mobile-userinfo-page {
  display: none;
  padding: 0 0.1rem 0.75rem;
  .title-box {
    padding: 0.2rem 0 0.17rem;
    font-size: 0.2rem;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #37383D;
    line-height: 0.28rem;
  }
  .title-sub {
    margin-top: 0.03rem;
    font-size: 0.13rem;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #9597A0;
    line-height: 0.18rem;
  }

  .step-box {
    position: fixed;
    display: flex;
    bottom: 0;
    left: 0;
    z-index: 1;
    padding: 0 0.15rem;
    width: 100%;
    height: 0.75rem;
    align-items: center;
    background-color: #fff;
  }
  .step-btn {
    flex: 1;
    height: 0.55rem;
    font-size: 0.18rem;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    line-height: 0.25rem;
    border-radius: 0.05rem;
    & + .step-btn {
      margin-left: 0.11rem;
    }
  }
  .step-up {
    color: #3D6CB0;
    border: 0.01rem solid #3D6CB0;
    background-color: #fff;
  }
  .step-next {
    background-color: #3D6CB0;
  }

  ::v-deep .van-form {
    .van-cell {
      padding: 0.15rem  0;
      font-size: 0.14rem;
      &::after {
        right: auto;
        left: auto;
        width: 100%;
      }
      .van-field__label {
        margin-right: 0;
        width: 0.85rem;
        font-size: 0.14rem;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #37383D;
        line-height: 0.3rem;
      }
      .van-field__control  {
        min-height: 0.3rem;
      }
      .van-field__right-icon {
        padding-left: 0;
      }
    }
    .van-radio-group--horizontal {
      justify-content: flex-end;
    }
    .van-radio--horizontal {
      margin-right: 0.1rem;
      min-width: 0.69rem;
    }
    .van-radio__label {
      line-height: 0.32rem;
    }
    .van-radio__icon,
    .van-checkbox__icon {
      font-size: 16px;
    }
    .form-item-input {
      &.disabled {
        background-color: #f1f1f1;
      }
      .van-field__body {
        border-radius: 0.02rem;
        border: 0.01rem solid #F0F0F0;
      }
      input {
        padding: 0.06rem 0.13rem;
        height: 0.32rem;
        font-size: 0.14rem;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        line-height: 0.2rem;
      }
      .van-icon {
        margin-right: 0.07rem;
      }
      &.van-field--error {
        .van-field__body {
          border-color: #ee0a24;
        }
      }
    }
    .form-item-right {
      .van-field__control,
      .van-radio--horizontal {
        justify-content: flex-end;
      }
    }
    .form-item-educational {
      .van-field__control--custom {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
      }
      .form-item-input {
        padding: 0;
      }
      input {
        padding-right: 0.1rem;
      }
      .van-radio--horizontal {
        min-width: 1.2rem;
      }
      &.van-field--error {
        .van-field__body {
          border-color: #ee0a24;
        }
      }
    }
    .form-item-educational-options {
      display: flex;
      margin-top: 0.14rem;
      flex-wrap: wrap;
      justify-content: flex-end;
      .van-radio__label {
        line-height: 0.2rem;
      }
    }
    .form-item-educational-tips {
      margin-top: 0.1rem;
      font-size: 0.12rem;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #B0B0B0;
      line-height: 0.17rem;
    }
    .form-item-times {
      display: flex;
      align-items: center;
    }
    .form-item-times-line {
      margin: 0 0.1rem;
    }
    .van-radio__icon--checked .van-icon {
      border-color: #4677B9;
      background-color: #4677B9;
    }
    .form-item-salary {
      display: flex;
      .van-field__label {
        display: flex;
      }
    }
    .form-item-salary-label {
      display: flex;
      align-items: center;
      flex-direction: column;
    }
    .form-item-tip {
      color:#B0B0B0;
      font-size: 0.12rem;
      line-height: 1;
    }
  }
}
</style>
